package com.example.larouzey.myapplication;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.cbtService.AndroidSDK.HardwareControler;
import com.example.larouzey.broadnotifytest_201ljy.R;

public class MainActivity extends AppCompatActivity {
    private TextView tv1,tv2,tv3;
    private int sessionID;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
                case 1:
                    byte[] d=(byte[]) msg.obj;
                    if(d[12]==(byte) 0x0A) {
                        tv1.setText((d[20] + d[19] * 256) / 10 + "C");
                        tv2.setText((d[18] + d[17] * 256) / 10 + "%");
                    }
                    break;
                case 2:
                    byte[] e=(byte[]) msg.obj;
                    if(e[12]==(byte) 0x0A) {
                        if(e[20]==(byte)0x01)
                        tv3.setText("有人");
                        else tv3.setText("无人");
                    }
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1=(TextView)findViewById(R.id.textView);
        tv2=(TextView)findViewById(R.id.textView2);
        tv3=(TextView)findViewById(R.id.textView3);
        sessionID= HardwareControler.openSerialPort("",115200,8,1);

        new Thread(){
            public void run(){
                while(true){
                    byte [] d=new byte[1];
                    while(true){
                        HardwareControler.read(sessionID,d,1);
                        if(d[0]==0xee){
                            HardwareControler.read(sessionID,d,1);
                            if(d[0]==0xcc) {
                                HardwareControler.read(sessionID, d, 1);
                                byte [] data = new  byte[24];
                                HardwareControler.read(sessionID, d, 24);
                                if(d[12]==(byte)0x0A) {
                                    Message msg = new Message();
                                    msg.what = 1;
                                    msg.obj = data;
                                    handler.sendMessage(msg);
                                }else if(d[12]==(byte)0x07){
                                    Message msg = new Message();
                                    msg.what = 2;
                                    msg.obj = data;
                                    handler.sendMessage(msg);
                                }
                                break;
                            }
                            }
                    }

                }
            }
        }.start();
    }
}
